
#include "powderpot.h"
#include "resourcemanager.h"
#include "gamemanager.h"
#include "unit.h"
#include "enemy.h"
#include "animation.h"
#include "gameplayscene.h"

#define __super         Bullet

static const float POWDER_POT_BULLET_SPEED = 600.0f;

PowderPot::PowderPot(const Point& from, const Point& to) :
	gamePlayScene(nullptr)
{
	src = from;
	dst = to;
	position = src;

	damageRange = 50.0f;
}

PowderPot::~PowderPot() {
}

void PowderPot::init(GamePlayScene* scene) {
	__super::init();

	gamePlayScene = scene;

	sprite = CREATE_SPRITE("textures/fx/powder_pot.png");
	_halfPotLengh = sprite->getContentSize().width / 2.0f;

	float t = 0.6f;
	float velocity_x = (dst.x - src.x) / t;
	float fall_range = 0.5f * GRAVITY * t * t;
	float velocity_y = (dst.y - src.y - fall_range) / t;

	speed = Point(velocity_x, velocity_y);

	sprite->setPosition(SCALE_PT(src));
}

bool PowderPot::update(float ticks) {
	bool isArrivedTarget = false;

	Point realStep = speed * ticks;
	speed.y += GRAVITY * ticks;

	Point newPos = position + realStep;

	if(speed.y <= 0) {
		float distance = dst.getDistance(newPos);

		if(distance < _halfPotLengh) {
			isArrivedTarget = true;
			isHitTarget = true;
		} else if(newPos.y < dst.y) {
			isArrivedTarget = true;
		}
	}

	position = newPos;

	sprite->setPosition(SCALE_PT(position));

	if(isArrivedTarget) {
		// play frame animation
		AnimationInfo info = RM->animationInfos["explosion"];
		float delay = info.frames.size() * info.frameRate;

		FrameAnimation* animExplosion = RM->createAnimation("explosion", newPos);
		animExplosion->setZOrder(999);
		animExplosion->setTag(TAG_NO_ZORDER);
		animExplosion->isLoop = false;
		gamePlayScene->addFrameAnimations(animExplosion);

		// apply damage
		for(Enemy* enemy : gamePlayScene->enemies)  {
			if(enemy && enemy->isAlive()) {
				float distance = enemy->position.getDistance(position);
				if(distance < damageRange) {
					enemy->handleBulletHit(this, 1.0f - distance / damageRange);
				}
			}
		}
	}

	return !isArrivedTarget;
}
